package cn.iocoder.yudao.module.crm.controller.admin.customer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.poi.excel.ExcelWriter;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils;
import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.enums.ExcelColumn;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.ip.core.Area;
import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils;
import cn.iocoder.yudao.framework.mybatis.core.enums.QueryFieldType;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.crm.controller.admin.clue.vo.*;
import cn.iocoder.yudao.module.crm.controller.admin.customFieldHead.vo.CustomFieldHeadPageReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.customer.vo.customer.*;
import cn.iocoder.yudao.module.crm.controller.admin.importtask.vo.ImportTaskSaveReqVO;
import cn.iocoder.yudao.module.crm.dal.dataobject.clue.CrmClueDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.customFieldHead.CustomFieldHeadDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.customer.CrmCustomerDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.customer.CrmCustomerPoolConfigDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.label.CrmLabelDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.levelconfig.CrmLevelConfigDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.mobileencryptconfig.MobileEncryptConfigDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.module.CrmModuleDO;
import cn.iocoder.yudao.module.crm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.crm.enums.customField.FieldEnum;
import cn.iocoder.yudao.module.crm.mq.message.CrmCustomerDistributeMessage;
import cn.iocoder.yudao.module.crm.mq.producer.CrmCustomerDistributeProducer;
import cn.iocoder.yudao.module.crm.service.customFieldHead.CustomFieldHeadService;
import cn.iocoder.yudao.module.crm.service.customer.CrmCustomerPoolConfigService;
import cn.iocoder.yudao.module.crm.service.customer.CrmCustomerService;
import cn.iocoder.yudao.module.crm.service.customfieldData.CustomFieldDataService;
import cn.iocoder.yudao.module.crm.service.importtask.ImportTaskService;
import cn.iocoder.yudao.module.crm.service.levelconfig.CrmLevelConfigService;
import cn.iocoder.yudao.module.crm.service.mobileencryptconfig.MobileEncryptConfigService;
import cn.iocoder.yudao.module.crm.service.module.CrmModuleService;
import cn.iocoder.yudao.module.crm.util.CrmExcelUtil;
import cn.iocoder.yudao.module.crm.util.ExcelParseUtil;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.alibaba.excel.annotation.ExcelProperty;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Stream;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.pojo.PageParam.PAGE_SIZE_NONE;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.crm.enums.DictTypeConstants.*;
import static java.util.Collections.singletonList;

@Tag(name = "管理后台 - CRM 客户")
@RestController
@RequestMapping("/crm/customer")
@Validated
public class CrmCustomerController {

    @Resource
    private CrmCustomerService customerService;
    @Resource
    private CrmCustomerPoolConfigService customerPoolConfigService;

    @Resource
    private DeptApi deptApi;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private DictDataApi dictDataApi;

    @Resource
    private CrmModuleService moduleService;

    @Resource
    private ImportTaskService importTaskService;

    @Resource
    private CrmLevelConfigService levelConfigService;

    @Resource
    private MobileEncryptConfigService mobileEncryptConfigService;

    @Resource
    private CustomFieldDataService customFieldDataService;

    @Resource
    private CustomFieldHeadService customFieldHeadService;

    @Resource
    private CrmCustomerDistributeProducer distributeProducer;

    @PostMapping("/create")
    @Operation(summary = "创建客户")
    @PreAuthorize("@ss.hasPermission('crm:customer:create')")
    public CommonResult<Long> createCustomer(@Valid @RequestBody CrmCustomerSaveReqVO createReqVO) {
        return success(customerService.createCustomer(createReqVO, getLoginUserId()));
    }

    @PutMapping("/update")
    @Operation(summary = "更新客户")
    @PreAuthorize("@ss.hasPermission('crm:customer:update')")
    public CommonResult<Boolean> updateCustomer(@Valid @RequestBody CrmCustomerSaveReqVO updateReqVO) {
        customerService.updateCustomer(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-we-customer")
    @Operation(summary = "更新客户")
    @PreAuthorize("@ss.hasPermission('crm:customer:update')")
    public CommonResult<Boolean> updateCustomer(@Valid @RequestBody CrmCustomerUpdateReqVO updateReqVO) {
        customerService.updateCustomer(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-deal-status")
    @Operation(summary = "更新客户的成交状态")
    @Parameters({
            @Parameter(name = "id", description = "客户编号", required = true),
            @Parameter(name = "dealStatus", description = "成交状态", required = true)
    })
    public CommonResult<Boolean> updateCustomerDealStatus(@RequestParam("id") Long id,
                                                          @RequestParam("dealStatus") Boolean dealStatus) {
        customerService.updateCustomerDealStatus(id, dealStatus);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除客户")
    @Parameter(name = "id", description = "客户编号", required = true)
    @PreAuthorize("@ss.hasPermission('crm:customer:delete')")
    public CommonResult<Boolean> deleteCustomer(@RequestParam("id") Long id) {
        customerService.deleteCustomer(id);
        return success(true);
    }

    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除客户")
    @Parameter(name = "ids", description = "客户编号", required = true)
    @PreAuthorize("@ss.hasPermission('crm:customer:delete')")
    public CommonResult<Boolean> batchDeleteCustomer(@RequestParam("ids") List<Long> ids) {
        customerService.batchDeleteCustomer(ids);
        return success(true);
    }

    @DeleteMapping("/delete-pool")
    @Operation(summary = "从公海删除客户")
    @Parameter(name = "id", description = "客户编号", required = true)
    @PreAuthorize("@ss.hasPermission('crm:customer:delete')")
    public CommonResult<Boolean> deleteCustomerPool(@RequestParam("id") Long id) {
        customerService.deleteCustomerPool(id);
        return success(true);
    }

    @DeleteMapping("/batch-delete-pool")
    @Operation(summary = "批量从公海删除客户")
    @Parameter(name = "ids", description = "客户编号", required = true)
    @PreAuthorize("@ss.hasPermission('crm:customer:delete')")
    public CommonResult<Boolean> deleteCustomerPool(@RequestParam("ids") List<Long> ids) {
        customerService.batchDeleteCustomerPool(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得客户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('crm:customer:query')")
    public CommonResult<JSONObject> getCustomer(@RequestParam("id") Long id) {
        // 1. 获取客户
        CrmCustomerDO customer = customerService.getCustomer(id);
        // 2. 拼接数据
        CrmCustomerRespVO crmCustomerRespVO = buildCustomerDetail(customer);
        List<JSONObject> advanceCustomFieldDataCustomer = customFieldDataService.getAdvanceCustomFieldDataCustomer(Arrays.asList(crmCustomerRespVO));
        return success(advanceCustomFieldDataCustomer.get(0));
    }

    public CrmCustomerRespVO buildCustomerDetail(CrmCustomerDO customer) {
        if (customer == null) {
            return null;
        }
        return buildCustomerDetailList(singletonList(customer)).get(0);
    }

    @PostMapping("/advance-page")
    @Operation(summary = "高级查询-获得线索分页")
    @PreAuthorize("@ss.hasPermission('crm:customer:query')")
    public CommonResult<PageResult<JSONObject>> getClueAdvancePage(@Valid @RequestBody PageParam pageVO) {
        PageResult<CrmCustomerDO> pageResult = customerService.getCustomerAdvancePage(pageVO, getLoginUserId());
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty(pageResult.getTotal()));
        }
        // 2. 拼接数据
        List<CrmCustomerRespVO> crmCustomerRespVOS = buildCustomerDetailList(pageResult.getList());
        List<JSONObject> advanceCustomFieldDataCustomer = customFieldDataService.getAdvanceCustomFieldDataCustomer(crmCustomerRespVOS);
        return success(new PageResult<>(advanceCustomFieldDataCustomer, pageResult.getTotal()));
    }

    @PostMapping("/custom-advance-page")
    @Operation(summary = "自定义高级查询-获得线索分页")
    @PreAuthorize("@ss.hasPermission('crm:customer:query')")
    public CommonResult<PageResult<JSONObject>> getCustomClueAdvancePage(@Valid @RequestBody PageParam pageVO) {
        PageResult<CrmCustomerDO> pageResult = customerService.getCustomerAdvancePage(pageVO, getLoginUserId());
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty(pageResult.getTotal()));
        }
        // 2. 拼接数据
        List<CrmCustomerRespVO> crmCustomerRespVOS = buildCustomerDetailList(pageResult.getList());
        List<JSONObject> advanceCustomFieldDataCustomer = customFieldDataService.getAdvanceCustomFieldDataCustomer(crmCustomerRespVOS);
        return success(new PageResult<>(advanceCustomFieldDataCustomer, pageResult.getTotal()));
    }

    @GetMapping("/page")
    @Operation(summary = "获得客户分页")
    @PreAuthorize("@ss.hasPermission('crm:customer:query')")
    public CommonResult<PageResult<JSONObject>> getCustomerPage(@Valid CrmCustomerPageReqVO pageVO) {
        // 1. 查询客户分页
        PageResult<CrmCustomerDO> pageResult = customerService.getCustomerPage(pageVO, getLoginUserId());
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty(pageResult.getTotal()));
        }
        // 2. 拼接数据
        List<CrmCustomerRespVO> crmCustomerRespVOS = buildCustomerDetailList(pageResult.getList());
        List<JSONObject> advanceCustomFieldDataCustomer = customFieldDataService.getAdvanceCustomFieldDataCustomer(crmCustomerRespVOS);
        return success(new PageResult<>(advanceCustomFieldDataCustomer, pageResult.getTotal()));
    }

    public List<CrmCustomerRespVO> buildCustomerDetailList(List<CrmCustomerDO> list) {
        if (CollUtil.isEmpty(list)) {
            return java.util.Collections.emptyList();
        }
        // 1.1 获取创建人、负责人列表
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(convertListByFlatMap(list,
                contact -> Stream.of(NumberUtils.parseLong(contact.getCreator()), contact.getOwnerUserId())));
        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap(convertSet(userMap.values(), AdminUserRespDTO::getDeptId));
        // 1.2 获取距离进入公海的时间
        Map<Long, Long> poolDayMap = getPoolDayMap(list);
        // 1.3 查询模块
        Map<Long, CrmModuleDO> moduleMap = moduleService.getModuleMap(convertSet(list, CrmCustomerDO::getModuleId));

        // 1.4 查询客户等级
        Map<Long, CrmLevelConfigDO> levelMap = levelConfigService.getLevelConfigMap(convertSet(list, CrmCustomerDO::getLevelId));

        MobileEncryptConfigDO useEncrypt = mobileEncryptConfigService.useEncrypt();

        // 2. 转换成 VO
        return BeanUtils.toBean(list, CrmCustomerRespVO.class, customerVO -> {
            customerVO.setAreaName(AreaUtils.format(customerVO.getAreaId()));
            // 2.1 设置创建人、负责人名称
            MapUtils.findAndThen(userMap, NumberUtils.parseLong(customerVO.getCreator()),
                    user -> customerVO.setCreatorName(user.getNickname()));
            MapUtils.findAndThen(userMap, customerVO.getOwnerUserId(), user -> {
                customerVO.setOwnerUserName(user.getNickname());
                MapUtils.findAndThen(deptMap, user.getDeptId(), dept -> customerVO.setOwnerUserDeptName(dept.getName()));
            });
            // 2.2 设置距离进入公海的时间
            if (customerVO.getOwnerUserId() != null) {
                customerVO.setPoolDay(poolDayMap.get(customerVO.getId()));
            }
            // 2.3 查询所属模块
            MapUtils.findAndThen(moduleMap, customerVO.getModuleId(), module -> {
                customerVO.setModuleName(module.getName());
            });
            // 2.4 设置客户等级
            MapUtils.findAndThen(levelMap, customerVO.getLevelId(), customerVO::setLevelRespVO);
            // 2.5 计算是否加密
            customerVO.calculateProfile();

            customerVO.setEncryptMobile(mobileEncryptConfigService.convertEncryptMobile(useEncrypt, customerVO.getMobile()));
            customerVO.setEncryptTelephone(mobileEncryptConfigService.convertEncryptMobile(useEncrypt, customerVO.getTelephone()));
        });
    }

    @GetMapping("/put-pool-remind-page")
    @Operation(summary = "获得待进入公海客户分页")
    @OperateLog(enable = false)
    @PreAuthorize("@ss.hasPermission('crm:customer:query')")
    public CommonResult<PageResult<CrmCustomerRespVO>> getPutPoolRemindCustomerPage(@Valid CrmCustomerPageReqVO pageVO) {
        // 1. 查询客户分页
        PageResult<CrmCustomerDO> pageResult = customerService.getPutPoolRemindCustomerPage(pageVO, getLoginUserId());
        // 2. 拼接数据
        return success(new PageResult<>(buildCustomerDetailList(pageResult.getList()), pageResult.getTotal()));
    }

    @GetMapping("/put-pool-remind-count")
    @Operation(summary = "获得待进入公海客户数量")
    @OperateLog(enable = false)
//    @PreAuthorize("@ss.hasPermission('crm:customer:query')")
    public CommonResult<Map<Long, Long>> getPutPoolRemindCustomerCount() {
        return success(customerService.getPutPoolRemindCustomerCount(getLoginUserId()));
    }

    @GetMapping("/today-contact-count")
    @Operation(summary = "获得今日需联系客户数量")
    @OperateLog(enable = false)
    public CommonResult<Long> getTodayContactCustomerCount() {
        return success(customerService.getTodayContactCustomerCount(getLoginUserId()));
    }

    @GetMapping("/overdue-contact-count")
    @Operation(summary = "获得逾期联系客户数量")
    @OperateLog(enable = false)
    public CommonResult<Long> getOverdueContactCustomerCount() {
        return success(customerService.getOverdueContactCustomerCount(getLoginUserId()));
    }

    @GetMapping("/follow-count")
    @Operation(summary = "获得分配给我、待跟进的线索数量的客户数量")
    @OperateLog(enable = false)
    public CommonResult<Long> getFollowCustomerCount() {
        return success(customerService.getFollowCustomerCount(getLoginUserId()));
    }

    /**
     * 获取距离进入公海的时间 Map
     *
     * @param list 客户列表
     * @return key 客户编号, value 距离进入公海的时间
     */
    private Map<Long, Long> getPoolDayMap(List<CrmCustomerDO> list) {
        List<CrmCustomerPoolConfigDO> poolConfigList = customerPoolConfigService.getCustomerPoolList();
        if (CollUtil.isEmpty(poolConfigList)) {
            return MapUtil.empty();
        }
        Map<Long, CrmCustomerPoolConfigDO> poolMap = convertMap(poolConfigList, CrmCustomerPoolConfigDO::getId);
        list = CollectionUtils.filterList(list, customer -> {
            // 特殊：如果没负责人，则说明已经在公海，不用计算
            if (customer.getOwnerUserId() == null) {
                return false;
            }
            // 已成交 or 已锁定，不进入公海
            return !customer.getDealStatus() && !customer.getLockStatus();
        });
        return convertMap(list, CrmCustomerDO::getId, customer -> {
            CrmCustomerPoolConfigDO poolConfig = poolMap.get(customer.getModuleId());
            if (Objects.isNull(poolConfig)) {
                return 0L;
            }
            // 1.1 未成交放入公海天数
            long dealExpireDay = poolConfig.getDealExpireDays() - LocalDateTimeUtils.between(customer.getOwnerTime());
            // 1.2 未跟进放入公海天数
            LocalDateTime lastTime = customer.getOwnerTime();
            if (customer.getContactLastTime() != null && customer.getContactLastTime().isAfter(lastTime)) {
                lastTime = customer.getContactLastTime();
            }
            long contactExpireDay = poolConfig.getContactExpireDays() - LocalDateTimeUtils.between(lastTime);
            // 2. 返回最小的天数
            long poolDay = Math.min(dealExpireDay, contactExpireDay);
            return poolDay > 0 ? poolDay : 0;

        });
    }

    @GetMapping(value = "/simple-list")
    @Operation(summary = "获取客户精简信息列表", description = "只包含有读权限的客户，主要用于前端的下拉选项")
    public CommonResult<List<CrmCustomerRespVO>> getCustomerSimpleList() {
        CrmCustomerPageReqVO reqVO = new CrmCustomerPageReqVO();
        reqVO.setPageSize(PAGE_SIZE_NONE); // 不分页
        List<CrmCustomerDO> list = customerService.getCustomerPage(reqVO, getLoginUserId()).getList();
        return success(convertList(list, customer -> // 只返回 id、name 精简字段
                new CrmCustomerRespVO().setId(customer.getId()).setName(customer.getName()).setModuleId(customer.getModuleId())));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出客户 Excel")
    @PreAuthorize("@ss.hasPermission('crm:customer:export')")
    @OperateLog(type = EXPORT)
    public void exportCustomerExcel(@Valid CrmCustomerPageReqVO pageVO,
                                    HttpServletResponse response) throws IOException {
        pageVO.setPageSize(PAGE_SIZE_NONE); // 不分页
        List<CrmCustomerDO> list = customerService.getCustomerPage(pageVO, getLoginUserId()).getList();
        // 导出 Excel
        ExcelUtils.write(response, "客户.xlsx", "数据", CrmCustomerRespVO.class,
                buildCustomerDetailList(list));
    }

    @GetMapping("/custom-export-excel")
    @Operation(summary = "导出线索 Excel")
    @PreAuthorize("@ss.hasPermission('crm:clue:export')")
    @OperateLog(type = EXPORT)
    public void customExportClueExcel(@Valid CrmCustomerPageReqVO pageReqVO, HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PAGE_SIZE_NONE);
        List<CrmCustomerDO> crmClueDOList = customerService.getCustomerPage(pageReqVO, getLoginUserId()).getList();
        List<CrmCustomerRespVO> crmCustomerRespVOS = buildCustomerDetailList(crmClueDOList);
        List<JSONObject> advanceCustomFieldData = customFieldDataService.getAdvanceCustomFieldDataCustomer(crmCustomerRespVOS);
        List<CustomFieldHeadDO> headList = new ArrayList<>();
        Class<CrmClueRespVO> userClass = CrmClueRespVO.class;
        for (Field field : userClass.getDeclaredFields()) {
            // 检查字段是否包含 @MyAnnotation 注解
            if (field.isAnnotationPresent(ExcelProperty.class)) {
                // 获取注解实例
                ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
                // 获取注解的 value 值
                String[] value = annotation.value();
                // 打印字段名和注解的 value 值
                System.out.println("字段名: " + field.getName() + ", 注解 value: " + value[0]);
                CustomFieldHeadDO customFieldHeadDO = new CustomFieldHeadDO();
                customFieldHeadDO.setFieldName(field.getName());
                customFieldHeadDO.setName(value[0]);
                headList.add(customFieldHeadDO);
            }
        }
        CustomFieldHeadPageReqVO headPageReqVO = new CustomFieldHeadPageReqVO();
        if (null != pageReqVO.getModuleId()) {
            headPageReqVO.setModuleId(pageReqVO.getModuleId());
        }
        headPageReqVO.setTableType("1");
        List<CustomFieldHeadDO> customFieldHeadList = customFieldHeadService.getCustomFieldHeadList(headPageReqVO);
        if (CollUtil.isNotEmpty(customFieldHeadList)) {
            headList.addAll(customFieldHeadList);
        }
        ExcelParseUtil.exportExcel(advanceCustomFieldData, headList, "线索数据", response);
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入客户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<CrmCustomerImportExcelVO> list = Arrays.asList(
                CrmCustomerImportExcelVO.builder().name("数创万维").source(1)
                        .mobile("18888882555").email("xx@xx.com")
                        .remark("").build()
        );
        // 输出
        ExcelUtils.write(response, "客户导入模板.xlsx", "客户列表", CrmCustomerImportExcelVO.class, list, builderSelectMap());
    }

    @PostMapping("/get-custom-import-template")
    public void downloadExcel(Long moduleId, HttpServletResponse response) throws IOException {
        List<CrmModelFiledVO> crmModelFiledList = new ArrayList<>();
        List<String> dictDataLabelList = dictDataApi.getDictDataLabelList(CRM_CUSTOMER_SOURCE);
        // 获取 User 类的 Class 对象
        Class<CrmCustomerImportExcelVO> userClass = CrmCustomerImportExcelVO.class;

        // 遍历所有字段
        for (Field field : userClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(ExcelProperty.class)) {
                // 获取注解实例
                ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
                // 获取注解的 value 值
                String[] value = annotation.value();
                // 打印字段名和注解的 value 值
                if (field.getName().equals("source")) {
                    crmModelFiledList.add(new CrmModelFiledVO(field.getName(), FieldEnum.SELECT, value[0], 1, dictDataLabelList).setIsNull(0));
                } else if (field.getName().equals("remark")) {
                    continue;
                } else if (field.getName().equals("name")) {
                    crmModelFiledList.add(new CrmModelFiledVO(field.getName(), FieldEnum.TEXT, value[0], 1).setIsNull(1));
                } else {
                    crmModelFiledList.add(new CrmModelFiledVO(field.getName(), FieldEnum.TEXT, value[0], 1).setIsNull(0));
                }
            }
        }
        crmModelFiledList.add(new CrmModelFiledVO("remark", FieldEnum.TEXT, "备注", 1).setIsNull(0));
        CustomFieldHeadPageReqVO pageReqVO = new CustomFieldHeadPageReqVO();
        pageReqVO.setModuleId(moduleId);
        pageReqVO.setTableType("1");
        List<CustomFieldHeadDO> customFieldHeadList = customFieldHeadService.getCustomFieldHeadList(pageReqVO);
        if (CollUtil.isNotEmpty(customFieldHeadList)) {
            for (CustomFieldHeadDO customFieldHeadDO : customFieldHeadList) {
                if (customFieldHeadDO.getFieldType().equals(QueryFieldType.SELECT)) {
                    String expansion = customFieldHeadDO.getExpansion();
                    crmModelFiledList.add(new CrmModelFiledVO(customFieldHeadDO.getFieldName(), FieldEnum.TEXT, customFieldHeadDO.getName(), 0, Arrays.asList(expansion.split(","))).setIsNull(customFieldHeadDO.getIsRepeat()));
                } else if (customFieldHeadDO.getFieldType().equals(QueryFieldType.TIME)) {
                    crmModelFiledList.add(new CrmModelFiledVO(customFieldHeadDO.getFieldName(), FieldEnum.TIME, customFieldHeadDO.getName(), 0).setIsNull(customFieldHeadDO.getIsRepeat()));
                } else {
                    crmModelFiledList.add(new CrmModelFiledVO(customFieldHeadDO.getFieldName(), FieldEnum.TEXT, customFieldHeadDO.getName(), 0).setIsNull(customFieldHeadDO.getIsRepeat()));
                }
            }
        }
        crmModelFiledList.add(new CrmModelFiledVO("mapAddress", FieldEnum.MAP_ADDRESS, "地区定位", 1).setIsNull(0));
        Area area = AreaUtils.getArea(Area.ID_CHINA);
        List<Area> children = area.getChildren();
        ExcelParseUtil.importExcel(new ExcelParseUtil.ExcelParseService() {
            @Override
            public String getExcelName() {
                return "客户";
            }

            @Override
            public int addCell(ExcelWriter writer, Integer x, Integer y, String fieldName) {
                if (writer == null) {
                    if ("mapAddress".equals(fieldName)) {
                        return 3;
                    }
                    return 0;
                }
                if ("mapAddress".equals(fieldName)) {
                    Workbook wb = writer.getWorkbook();
                    Sheet sheet = writer.getSheet();
                    int four = 4;
                    for (int i = 0; i < four; i++) {
                        writer.setColumnWidth(x + i, 20);
                    }
                    Cell cell1 = writer.getOrCreateCell(x, y);
                    cell1.setCellValue("省");
                    Cell cell2 = writer.getOrCreateCell(x + 1, y);
                    cell2.setCellValue("市");
                    Cell cell3 = writer.getOrCreateCell(x + 2, y);
                    cell3.setCellValue("区");
                    Cell cell4 = writer.getOrCreateCell(x + 3, y);
                    cell4.setCellValue("详细地址");
                    Sheet hideSheet = wb.createSheet(fieldName);
                    wb.setSheetHidden(wb.getSheetIndex(hideSheet), true);
                    int rowId = 0;
                    // 设置第一行，存省的信息
                    Row provinceRow = hideSheet.createRow(rowId++);
                    provinceRow.createCell(0).setCellValue("省列表");
                    String[] provinceList = children.stream()
                            .map(Area::getName)
                            .toArray(String[]::new);
                    for (int line = 0; line < provinceList.length; line++) {
                        Cell provinceCell = provinceRow.createCell(line + 1);
                        provinceCell.setCellValue(provinceList[line]);
                    }
                    // 将具体的数据写入到每一行中，行开头为父级区域，后面是子区域。
                    Map<String, List<String>> areaMap = CrmExcelUtil.getAreaMap();
                    Assert.notNull(area, "获取不到中国");

//                    Map<String, List<String>> areaMap= BeanUtils.toBean(children, Map.class);
                    for (String key : areaMap.keySet()) {
                        List<String> son = areaMap.get(key);
                        Row subRow = hideSheet.createRow(rowId++);
                        subRow.createCell(0).setCellValue(key);
                        for (int line = 0; line < son.size(); line++) {
                            Cell cell = subRow.createCell(line + 1);
                            cell.setCellValue(son.get(line));
                        }
                        // 添加名称管理器
                        String range = CrmExcelUtil.getRange(1, rowId, son.size());
                        Name name = wb.createName();
                        // key不可重复
                        name.setNameName(key);
                        String formula = fieldName + "!" + range;
                        name.setRefersToFormula(formula);
                    }
                    // 省级下拉框
                    CellRangeAddressList provRangeAddressList = new CellRangeAddressList(2, 10004, x, x);
                    DataValidationHelper validationHelper = sheet.getDataValidationHelper();
                    DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(provinceList);
                    //设置下拉框数据
                    DataValidation dataValidation = validationHelper.createValidation(constraint, provRangeAddressList);
                    dataValidation.createErrorBox("error", "请选择正确的省份");
                    sheet.addValidationData(dataValidation);
                    //市 区下拉框
                    int forIndex = 10004;
                    for (int line = 2; line < forIndex; line++) {
                        CrmExcelUtil.setDataValidation(CrmExcelUtil.getCorrespondingLabel(x + 1), sheet, line, x + 1);
                        CrmExcelUtil.setDataValidation(CrmExcelUtil.getCorrespondingLabel(x + 2), sheet, line, x + 2);
                    }
                    return 3;
                }
                return 0;
            }
        }, crmModelFiledList, response, "crm");
    }

    private List<KeyValue<ExcelColumn, List<String>>> builderSelectMap() {
        List<KeyValue<ExcelColumn, List<String>>> selectMap = new ArrayList<>();
        // 获取地区下拉数据
//        Area area = AreaUtils.getArea(Area.ID_CHINA);
//        selectMap.add(new KeyValue<>(ExcelColumn.G, AreaUtils.getAreaNodePathList(area.getChildren())));
        // 获取客户来源
        List<String> customerSources = dictDataApi.getDictDataLabelList(CRM_CUSTOMER_SOURCE);
        selectMap.add(new KeyValue<>(ExcelColumn.D, customerSources));
        return selectMap;
    }

    @PostMapping("/import")
    @Operation(summary = "导入客户")
    @OperateLog(enable = false)
    @PreAuthorize("@ss.hasPermission('crm:customer:import')")
    public CommonResult<Boolean> importExcel(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "repeatHandleField", required = false) Integer repeatHandleField,
            @RequestParam(value = "repeatHandleType", required = false) Integer repeatHandleType,
            @RequestParam(value = "ownerUserId", required = false) Long ownerUserId,
            @RequestParam(value = "moduleId") Long moduleId,
            @RequestParam(value = "pool", required = false) Boolean pool
    )
            throws Exception {
        if (Objects.isNull(ownerUserId) && !pool) {
            ownerUserId = getLoginUserId();
        }
        try {
            File file1 = FileUtil.createTempFile("crm-import-files", file.getOriginalFilename(), false);
            FileUtil.writeBytes(file.getBytes(), file1.getPath());
            @Valid ImportTaskSaveReqVO importTaskSaveReqVO = new ImportTaskSaveReqVO();
            importTaskSaveReqVO.setBizType(CrmBizTypeEnum.CRM_CUSTOMER.getType());
            importTaskSaveReqVO.setStatus(0);
            importTaskSaveReqVO.setPool(pool ? 1 : 0);
            importTaskSaveReqVO.setFileName(file.getOriginalFilename());
            importTaskSaveReqVO.setFilePath(file1.getPath());
            importTaskSaveReqVO.setModuleId(moduleId);
            importTaskSaveReqVO.setRepeatField(repeatHandleField);
            importTaskSaveReqVO.setRepeatHandle(repeatHandleType);
            importTaskSaveReqVO.setOwnerUserId(ownerUserId);
            importTaskService.createImportTask(importTaskSaveReqVO);
        } catch (Exception e) {
            throw exception(new ErrorCode(100500, e.getMessage()));
        }

//        CrmCustomerImportReqVO importReqVO = CrmCustomerImportReqVO.builder()
//                .ownerUserId(ownerUserId)
//                .file(file)
//                .repeatHandleField(repeatHandleField)
//                .repeatHandleType(repeatHandleType)
//                .moduleId(moduleId)
//                .pool(pool)
//                .build();
//        List<CrmCustomerImportExcelVO> list = ExcelUtils.read(importReqVO.getFile(), CrmCustomerImportExcelVO.class);
//        return success(customerService.importCustomerList(list, importReqVO));
        return success(true);
    }

    @PutMapping("/transfer")
    @Operation(summary = "转移客户")
    @PreAuthorize("@ss.hasPermission('crm:customer:update')")
    public CommonResult<Boolean> transferCustomer(@Valid @RequestBody CrmCustomerTransferReqVO reqVO) {
        customerService.transferCustomer(reqVO, getLoginUserId());
        return success(true);
    }

    @PutMapping("/batch-transfer")
    @Operation(summary = "转移客户")
    @PreAuthorize("@ss.hasPermission('crm:customer:update')")
    public CommonResult<Boolean> batchTransferCustomer(@Valid @RequestBody CrmCustomerBatchTransferReqVO reqVO) {
        Long userId = getLoginUserId();
        CrmCustomerTransferReqVO reqVO1 = new CrmCustomerTransferReqVO().setOldOwnerPermissionLevel(reqVO.getOldOwnerPermissionLevel()).setNewOwnerUserId(reqVO.getNewOwnerUserId());
        reqVO.getIds().forEach(id -> {
            reqVO1.setId(id);
            customerService.transferCustomer(reqVO1, userId);
        });
        return success(true);
    }

    @PutMapping("/lock")
    @Operation(summary = "锁定/解锁客户")
    @PreAuthorize("@ss.hasPermission('crm:customer:update')")
    public CommonResult<Boolean> lockCustomer(@Valid @RequestBody CrmCustomerLockReqVO lockReqVO) {
        customerService.lockCustomer(lockReqVO, getLoginUserId());
        return success(true);
    }

    @PutMapping("/batch-lock")
    @Operation(summary = "批量锁定/解锁客户")
    @PreAuthorize("@ss.hasPermission('crm:customer:update')")
    public CommonResult<Boolean> batchLockCustomer(@Valid @RequestBody CrmCustomerLockReqVO lockReqVO) {
        customerService.batchLockCustomer(lockReqVO, getLoginUserId());
        return success(true);
    }

    // ==================== 公海相关操作 ====================

    @PutMapping("/put-pool")
    @Operation(summary = "数据放入公海")
    @Parameter(name = "id", description = "客户编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('crm:customer:update')")
    public CommonResult<Boolean> putCustomerPool(@RequestParam("id") Long id) {
        customerService.putCustomerPool(id);
        return success(true);
    }

    @PutMapping("/batch-put-pool")
    @Operation(summary = "数据批量放入公海")
    @Parameter(name = "ids", description = "客户编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('crm:customer:update')")
    public CommonResult<Boolean> batchPutCustomerPool(@RequestParam("ids") List<Long> ids) {
        for (Long id : ids) {
            customerService.putCustomerPool(id);
        }
        return success(true);
    }

    @PutMapping("/receive")
    @Operation(summary = "领取公海客户")
    @Parameter(name = "ids", description = "编号数组", required = true, example = "1,2,3")
    @PreAuthorize("@ss.hasPermission('crm:customer:receive')")
    public CommonResult<Boolean> receiveCustomer(@RequestParam(value = "ids") List<Long> ids) {
        customerService.receiveCustomer(ids, Collections.singletonList(getLoginUserId()), Boolean.TRUE);
        return success(true);
    }

    @PutMapping("/distribute")
    @Operation(summary = "分配公海给对应负责人")
    @PreAuthorize("@ss.hasPermission('crm:customer:distribute')")
    public CommonResult<Boolean> distributeCustomer(@Valid @RequestBody CrmCustomerDistributeReqVO distributeReqVO) {
        customerService.receiveCustomer(distributeReqVO.getIds(), distributeReqVO.getOwnerUserIdList(), Boolean.FALSE);
        return success(true);
    }

    @PutMapping("/distributeBySize")
    @Operation(summary = "分配公海给对应负责人")
    @PreAuthorize("@ss.hasPermission('crm:customer:distribute')")
    public CommonResult<Boolean> distributeCustomerBySize(@RequestBody CrmCustomerDistributeReqVO distributeReqVO) {
        CrmCustomerDistributeMessage crmCustomerDistributeMessage = new CrmCustomerDistributeMessage();
        crmCustomerDistributeMessage.setDistributeReq(distributeReqVO);
        crmCustomerDistributeMessage.setOwnerUserIdList(distributeReqVO.getOwnerUserIdList());
        crmCustomerDistributeMessage.setIsReceive(Boolean.FALSE);
        distributeProducer.sendCrmCustomerDistributeMessage(crmCustomerDistributeMessage);
        return success(true);
    }

    @PostMapping("/customer-label")
    @Operation(summary = "获取客户标签")
    @OperateLog(enable = false)
    public CommonResult<Map<Long, List<CrmLabelDO>>> getCustomerLabel(@RequestBody CrmCustomerLabelReqVO reqVO) {
        return success(customerService.getCustomerLabelMap(reqVO.getIds()));
    }


    @PostMapping("/update-label")
    @Operation(summary = "保存客户标签")
    @OperateLog(enable = false)
    public CommonResult<Boolean> updateCustomerLabel(@RequestBody CrmCustomerLabelUpdateReqVO reqVO) {
        return success(customerService.updateCustomerLabel(reqVO));
    }

    @PostMapping("/batch-update-label")
    @Operation(summary = "批量添加客户标签， 不删除， 只添加新的")
    @OperateLog(enable = false)
    public CommonResult<Boolean> batchUpdateCustomerLabel(@RequestBody CrmCustomerLabelUpdateReqVO reqVO) {
        return success(customerService.batchUpdateClueLabel(reqVO));
    }


}
